package com.lhgray.sglhome.presentation.ui.compose

import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.lhgray.sglhome.domain.model.ListItemStatus
import com.lhgray.sglhome.domain.model.TruckingBean
import com.lhgray.sglhome.domain.model.UserData
import com.lhgray.sglhome.presentation.viewModel.HomeViewModel
import com.lhgray.sglhome.presentation.viewModel.TruckingViewModel

/**
 * 卡车的页面
 */
@Preview(showBackground = true)
@Composable
fun TruckingPreviewView() {

}



@Composable
fun TruckingPage(
    homeViewModel: HomeViewModel,
    onScanBarcode: () -> Unit,//跳转到扫一扫的页面的
    viewModel: TruckingViewModel = hiltViewModel()
) {

    val context = LocalContext.current
    val fileNo by homeViewModel.fileNo.collectAsStateWithLifecycle()
    val permissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissionsMap: Map<String,Boolean> ->
        val allPermissionsGranted = permissionsMap.values.all { it }
        if (allPermissionsGranted) {
            viewModel.getLastLocation(context){location ->
                viewModel.postTruckingJob(context,fileNo,location)
            }
        }
    }

    val truckingState by viewModel.uiState.collectAsStateWithLifecycle()
    var isVisible by remember { mutableStateOf(false) }
    var fileNoChangedWhileInvisible by remember { mutableStateOf(false) }
    val userData by homeViewModel.userData.collectAsStateWithLifecycle()

    homeViewModel.uploadLoadingOrError(
        truckingState.isLoading,
        truckingState.errorMsg ?: "",
        truckingState.toast
    )
    DisposableEffect(Unit) {
        isVisible = true
        onDispose { isVisible = false }
    }
    // 监听 fileNo 的变化
    LaunchedEffect(fileNo) {
        if (isVisible) {
            homeViewModel.uploadLoadingOrError(true, "")
            viewModel.getTruckingJob(fileNo)
        } else {
            fileNoChangedWhileInvisible = true
        }
    }
    // 监听页面可见性的变化
    LaunchedEffect(isVisible) {
        if (isVisible && fileNoChangedWhileInvisible) {
            homeViewModel.uploadLoadingOrError(true, "")
            viewModel.getTruckingJob(fileNo)
            fileNoChangedWhileInvisible = false
        }
    }
    Column(
        Modifier
            .background(color = Color.White)
            .fillMaxSize()
    ) {
        TruckingComposeHander(
            userData,
            fileNo, onScanBarcode
        ) {
            //homeViewModel.uploadLoading(true)
            homeViewModel.upFileNo(it)
            viewModel.getTruckingJob(it)

        }
        val truckingBean = truckingState.truckingBean
        if (truckingBean != null) {
            TruckingCompose(
                truckingBean,
            ) { index, data ->
                viewModel.saveTruckingJobIndex(index)
                if (ContextCompat.checkSelfPermission(
                        context,
                        Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    permissionLauncher.launch(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION) )
                } else {
                    viewModel.getLastLocation(context) { its ->
                        viewModel.postTruckingJob(context,fileNo,its)
                    }
                }
            }
        }
    }

}

@Composable
fun TruckingComposeHander(
    userData: UserData,
    fileNo: String, onScanBarcode: () -> Unit,//跳转到扫码
    onSearchNumber: (String) -> Unit,//输入框的数据进行搜索的
) {
    UserHandleView(userData)
    InputSearch(fileNo, onScanBarcode, onSearchNumber)
}

@Composable
fun TruckingCompose(
    uiTruckingFlow: TruckingBean,
    onclick: (Int, ListItemStatus) -> Unit
) {
    Column {
        //列表的数据
        LazyVerticalGrid(
            modifier = Modifier
                .fillMaxHeight(),
            columns = GridCells.Fixed(2),
            contentPadding = PaddingValues(15.dp)
        ) {
            itemsIndexed(
                uiTruckingFlow.list_item_label,
                span = { _, _ -> GridItemSpan(2) }) { _, item ->
                LazyColumnItemOrder(item)
            }
            itemsIndexed(uiTruckingFlow.list_item_status) { index, item ->
                FunctionButtons(itemValue = item, index = index) {
                    onclick(index, item)
                }
            }
        }
    }
}

@Composable
fun FunctionButtons(
    modifier: Modifier = Modifier,
    itemValue: ListItemStatus?,
    index: Int,
    onclick: () -> Unit
) {
    val paddingValues = if (index % 2 == 1) {
        PaddingValues(start = 15.dp, top = 0.dp, end = 0.dp, bottom = 0.dp)
    } else {
        PaddingValues(start = 0.dp, top = 0.dp, end = 15.dp, bottom = 0.dp)
    }

    val buttonText = if (itemValue?.check_flag == 1) {
        buildAnnotatedString {
            withStyle(
                style = SpanStyle(
                    fontSize = 13.sp, fontWeight = FontWeight.Bold
                )
            ) { append(itemValue.show_title + "\n") }
            withStyle(
                style = SpanStyle(fontSize = 10.sp)
            ) { append(itemValue.check_date) }
        }
    } else {
        buildAnnotatedString {
            withStyle(
                style = SpanStyle(
                    fontSize = 15.sp, fontWeight = FontWeight.Bold
                )
            ) { append(itemValue?.show_title) }
        }

    }
    Column {
        HorizontalDivider(
            modifier = Modifier
                .fillMaxWidth()
                .height(1.dp),
            color = Color.Black.copy(alpha = 0.5f)
        )
        Spacer(modifier = Modifier.height(25.dp))

        Button(
            enabled = itemValue?.check_flag == 0,
            onClick = onclick,
            modifier = modifier
                .fillMaxSize()
                .padding(paddingValues)
                .height(65.dp),
            colors = if (index % 2 == 1) {
                ButtonDefaults.buttonColors(Color(0xFFd2f6ac))
            } else {
                ButtonDefaults.buttonColors(Color(0xFF4295e5))

            },
            shape = RoundedCornerShape(5.dp),
        ) {
            Text(
                text = buttonText,
                fontSize = 14.sp,// 设置按钮内文本的字体大小为 18sp)
            )
        }
        Spacer(modifier = Modifier.height(25.dp))
    }
}


